package com.wswy.wzcx.module;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.wswy.wzcx.ui.Constants;
import timber.log.Timber;

public class WService extends Service {

  private static final String TAG = "WService";

  private static final String LOW_TOKEN = "Nhmjs13Tg387Rfmbv--";
  private static final String JSCODE = "javascript:alert('"+LOW_TOKEN+"'+document.querySelector('meta[name=description]').getAttribute('content'))";

  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  private WebView webView;

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    Timber.e("onStartCommand --> "+intent);

    if (intent!= null && intent.hasExtra("url")) {

      final String url = intent.getStringExtra("url");
      String ua = intent.getStringExtra("ua");

      boolean clearCookies = intent.getBooleanExtra("clearCookies",false);

      try {

        webView = new WebView(getApplicationContext());
        webView.layout(0, 0, 1080, 1920);
        webView.setWillNotDraw(true);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setSupportZoom(false);

        //不加载图片
        webView.getSettings().setLoadsImagesAutomatically(false);
        //更好优化的话可以不加载css 字体等
        webView.addJavascriptInterface(new MyJavaScriptInterface(),"HtmlViewer");

        if (clearCookies){
          CookieManager.getInstance().removeAllCookie();
        }
        //CookieManager.getInstance().removeExpiredCookie();


        webView.getSettings().setUserAgentString(ua);
        webView.setWebChromeClient(new WebChromeClient(){

          @Override
          public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            try {
              //不为空，并且比token拼接的长
              if (!TextUtils.isEmpty(message) && message.startsWith(LOW_TOKEN) && message.length() > (LOW_TOKEN.length()+10)){
                sendCookie(url);
              }
            } catch (Throwable e) {
              e.printStackTrace();
            }

            try {
              result.confirm();
            } catch (Throwable e) {
              e.printStackTrace();
            }

            return true;
          }
        });
        webView.setWebViewClient(new WebViewClient() {

          @Override
          public void onPageFinished(WebView view,final String url) {
            super.onPageFinished(view, url);
            Timber.e("onPageFinished --> " + url);



            //view.loadUrl("javascript:window.HtmlViewer.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");

//            if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
//              view.evaluateJavascript(js,
//                  new ValueCallback<String>() {
//                    @Override
//                    public void onReceiveValue(String value) {
//
//                      Log.e(TAG, "onReceiveValue --> "+value);
//
//                      if (!TextUtils.isEmpty(value) && value.length() > 10){
//
//                      }
//                    }
//                  });
//            }else {
//
//            }
           // webView.loadUrl("javascript:alert( '"+LOW_TOKEN+"'+"+JSCODE+")");

            webView.loadUrl(JSCODE);
          }


        });

        webView.loadUrl(url);
      } catch (Throwable e) {
        e.printStackTrace();
      }

    }

    return super.onStartCommand(intent, flags, startId);
  }


  private void sendCookie(String url){
    String cookie = CookieManager.getInstance().getCookie(url);
    Timber.e("sendCookie --> " + cookie);
    Context context = getApplicationContext();
    Intent data = new Intent(context, WReceiver.class);
    data.setAction(Constants.ACTION_WEB_GW122_END);
    data.putExtra("cookie", cookie);
    data.putExtra("url", url);
    context.sendBroadcast(data);

    stopSelf();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();

    Timber.e("onDestroy ---");
    try {
      if (webView != null){
        webView.stopLoading();
        webView.destroy();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      webView = null;
    }

  }

  static class MyJavaScriptInterface{

    @JavascriptInterface
    public void showHTML(String html){
      Timber.e("showHTML  --> "+html);
    }

  }

}
